App.controller('stockTypeController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) {

    //$scope.tree = [];
    $scope.selectedTypeId = '';

    $scope.query = function () {
        Page.ajaxPost('stockType/tree.do', null, function(resp) {
            $scope.types = resp.data;
        });
    };

    $scope.query();

    $scope.add = function () {
        $scope.type = {};
        $scope.type.parentTypeId = $scope.selectedTypeId ;
        $scope.modal.setTitle('新增').show();
    };

    $scope.delete = function (row) {
        Page.confirm("确定要删除吗？", function() {
            Page.ajaxPost('stockType/delete.do', row, function() {
                $scope.query();
            });
        });
    };

    $scope.edit = function (row) {
        $scope.type = angular.copy(row);
        $scope.modal.setTitle('编辑').show();
    };

    $scope.save = function () {
        Page.ajaxPost($scope.type.typeId ? 'stockType/update.do' : 'stockType/add.do', $scope.type, function() {
            $scope.query();
            $scope.type = {};
            $scope.modal.hide();
        });
    };

    $scope.cancel = function () {
        $scope.type = {};
        $scope.modal.hide();
    };

    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        $("#type_table").treetable({ expandable: true }, false);
    });

    $("#type_table tbody").on("mousedown", "tr a", function(e) {
        if( !$(e.target.parentElement).hasClass('selected') ){
            $(".selected").not(this).removeClass("selected");
            $(this).toggleClass("selected");
        }
        $scope.clickA = true;
    });

    $("#type_table tbody").on("mousedown", "tr", function(e) {
        if( !$scope.clickA && typeof e.target.parentElement.firstElementChild.getElementsByTagName('a')[0] != 'undefined' ){
            e.target.parentElement.firstElementChild.getElementsByTagName('a')[0].click();
        }
        if( !$(e.target.parentElement).hasClass('selected') ){
            $(".selected").not(this).removeClass("selected");
            $(this).toggleClass("selected");
        }
        $scope.clickA = false;
    });

    $scope.select = function (typeId) {
        $scope.selectedTypeId = typeId;
    }

}]);